package com.jstyle.jclifexd.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextPaint;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;



import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.utils.ScreenUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class TrackHistoryGoogleActivity extends BaseActivity implements OnMapReadyCallback{

    @BindView(R.id.bt_goal_back)
    Button btGoalBack;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_share)
    ImageView ivShare;

    private final static int AMAP_LOADED = 2;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case AMAP_LOADED:
                    setupRecord();
                    break;
                default:
                    break;
            }
        }
    };
    private Polyline mOriginPolyline;
    private Marker mOriginStartMarker;
    private Marker mOriginEndMarker;
    private List<LatLng> mOriginLatLngList;
    private com.google.android.gms.maps.model.Polyline mMutablePolyline;

    private void setupRecord() {
        if(mOriginLatLngList==null||mOriginLatLngList.size()==0)return;
        LatLng startLatLng = mOriginLatLngList.get(0);
        LatLng endLatLng = mOriginLatLngList.get(mOriginLatLngList.size() - 1);
        addOriginTrace(startLatLng, endLatLng, mOriginLatLngList);
    }

    private static final String TAG = "TrackHistoryGoogleActiv";
    private void addOriginTrace(LatLng startPoint, LatLng endPoint,
                                List<LatLng> originList) {
       googleMap.addPolyline(new PolylineOptions().color(
                Color.GREEN).addAll(originList));
        googleMap.addMarker(new MarkerOptions().position(
                startPoint).icon(
                BitmapDescriptorFactory.fromResource(R.drawable.start)));
         googleMap.addMarker(new MarkerOptions().position(
                endPoint).icon(
                BitmapDescriptorFactory.fromResource(R.drawable.end)));
        float distance = 0;

        List<LatLng>latLngDistance=new ArrayList<>();
        for (int i = 0; i < mOriginLatLngList.size() - 1; i++) {
            LatLng firstLatLng = mOriginLatLngList.get(i);
            LatLng secondLatLng = mOriginLatLngList.get(i + 1);
            float[] results = new float[3];
            Location.distanceBetween(firstLatLng.latitude, firstLatLng.longitude, secondLatLng.latitude, secondLatLng.longitude, results);
            double betweenDis = results[0];
            distance = (float) (distance + betweenDis);
            Log.i(TAG, "addOriginTrace: "+distance);
            if (distance >= 1000) {
                distance = distance-1000;
                latLngDistance.add(secondLatLng);
            }
        }
        for(int i=0;i<latLngDistance.size();i++){
            //MapDistanceView mapDistanceView=new MapDistanceView(this,i+1);
            Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.track_history).copy(Bitmap.Config.ARGB_8888, true);;

            Bitmap maker=drawableToBitmap(bitmap,String.valueOf(i+1));
            googleMap.addMarker(new MarkerOptions().flat(false).position(latLngDistance.get(i)).icon(
                    BitmapDescriptorFactory.fromBitmap(maker)));
        }
        try {
            googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(getBounds(),
                    50));
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
    public  Bitmap drawableToBitmap(Bitmap bitmap,String title) {
        Canvas canvas = new Canvas(bitmap);
        Rect rect=new Rect();
        TextPaint textPaint = new TextPaint();
        textPaint.setAntiAlias(true);
        textPaint.setTextAlign(Paint.Align.CENTER);
        textPaint.setTextSize(ScreenUtils.dip2px(this,10));
        textPaint.setColor(Color.WHITE);
        textPaint.getTextBounds(title, 0, title.length(), rect);
        canvas.drawText(title, bitmap.getWidth()/2, bitmap.getHeight()/2+rect.height()/2 ,textPaint);

        return bitmap;
    }




    private LatLngBounds getBounds() {
        LatLngBounds.Builder b = LatLngBounds.builder();
        if (mOriginLatLngList == null) {
            return b.build();
        }
        for (int i = 0; i < mOriginLatLngList.size(); i++) {
            b.include(mOriginLatLngList.get(i));
        }
        return b.build();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_track_google_history);
        ButterKnife.bind(this);
        SupportMapFragment mapFragment =
                (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        btGoalBack.setText(getString(R.string.Track_history));
        ScreenUtils.setTitleTypeface(btGoalBack);
        init();
    }

    private void init() {
        mOriginLatLngList= (List<LatLng>) getIntent().getSerializableExtra("track");
    }

    @OnClick(R.id.iv_back)
    public void onViewClicked() {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }


    GoogleMap googleMap;
    @Override
    public void onMapReady(GoogleMap googleMap) {
        int color = Color.GREEN;
        this.googleMap=googleMap;
        mMutablePolyline = googleMap.addPolyline(new PolylineOptions()
                .color(color)
                .clickable(true)
                .addAll(mOriginLatLngList));

        Message msg = handler.obtainMessage();
        msg.what = AMAP_LOADED;
        handler.sendMessage(msg);
    }

}
